/*
 * Copyright (c) 2013-2015 Charkey. All rights reserved.
 *
 * This software is the confidential and proprietary information of Charkey.
 * You shall not disclose such Confidential Information and shall use it only
 * in accordance with the terms of the agreements you entered into with Charkey.
 *
 * Charkey MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF THE SOFTWARE,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT.
 *
 * Charkey SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING,
 * MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES.
 */

package cn.simastudio.talos.common.logback.listener;

import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.classic.joran.JoranConfigurator;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.ResourceUtils;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import java.net.URL;

/**
 * Usage: LogbackConfigListener，设置 Logback 配置文件
 *
 * @author Charkey
 * @date 2015/4/1 16:56
 */
public class LogbackConfigListener implements ServletContextListener {

    /**
     * 日志logger
     */
    private static final Logger LOGGER = LoggerFactory.getLogger(LogbackConfigListener.class);

    public void contextInitialized(ServletContextEvent servletContextEvent) {
        // 读取注册 LogbackConfigListener 时设置的初始化参数 logbackConfigLocation
        String logbackConfigLocation = servletContextEvent.getServletContext().getInitParameter("logbackConfigLocation");
        if (!StringUtils.isEmpty(logbackConfigLocation)) {
            try {
                LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory();
                loggerContext.reset();
                JoranConfigurator joranConfigurator = new JoranConfigurator();
                joranConfigurator.setContext(loggerContext);
                URL logbackConfigUrl = ResourceUtils.getURL(logbackConfigLocation);
                joranConfigurator.doConfigure(logbackConfigUrl);
                if (LOGGER.isDebugEnabled()) {
                    LOGGER.debug("Logback configuration file loaded from {}", logbackConfigUrl);
                }
            } catch (Exception e) {
                if (LOGGER.isErrorEnabled()) {
                    LOGGER.error("Can't load logback configuration file from {}", e);
                }
            }
        } else {
            if (LOGGER.isErrorEnabled()) {
                LOGGER.error("InitParameter logbackConfigLocation for LogbackConfigListener is not configured!");
            }
        }
    }

    public void contextDestroyed(ServletContextEvent servletContextEvent) {

    }
}